package me.youline.dataServer.dao;


import java.sql.ResultSet;
import java.sql.SQLException;

import me.youline.dataServer.entity.UserSocialConnect;
import me.youline.dataServer.entity.UserSocialConnect.ConnectType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

/**
 * 社交账号关联平台用户信息DAO
 * @author linhan
 *
 */
@Component
public class UserSocialConnectDAO {

	private static String TABLE_NAME = "yline_base_socialConnect";
	
	@Autowired
	private JdbcTemplate template;
	
	private static final String QUERY_SQL = "select * from "+TABLE_NAME+" where socialConnectId = ? and connectType = ?";
	
	private static final String INSERT_SQL = "insert into "+TABLE_NAME + " (socialConnectId,connectType,userId) values(?,?,?) ";
	
	private RowMapper<UserSocialConnect> MAPPER = new RowMapper<UserSocialConnect>() {

		@Override
		public UserSocialConnect mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			UserSocialConnect connect = new UserSocialConnect();
			connect.setUserId(rs.getLong("userId"));
			connect.setSocialConnectId(rs.getString("socialConnectId"));
			connect.setConnectType(ConnectType.values()[rs.getInt("connectType")]);
			return connect;
		}
	};
	
	/**
	 * 根据社交账户ID，及第三方平台类型获取关联信息
	 * @param socialId
	 * @param type
	 * @return
	 */
	public UserSocialConnect getConnectBySocialId(String socialId,ConnectType type){
		try {
			return template.queryForObject(QUERY_SQL, new Object[]{socialId,type.ordinal()}, MAPPER);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}
	
	/**
	 * 增加第三方账号与用户关联信息
	 * 
	 * @param connect
	 */
	public void addSocialConnect(UserSocialConnect connect){
		template.update(INSERT_SQL, new Object[]{connect.getSocialConnectId(),connect.getConnectType().ordinal(),connect.getUserId()});
	}
	
	
}
